import { FORM_STATUS } from '@/utils/consts';

export default (opt = {
  listenChange: true// 监听组件是否有过输入
}) => ({
  data() {
    return {
      FORM_STATUS,
      state: FORM_STATUS.add,
      loading: false,
      visible: false,
      isChanged: false
    };
  },
  watch: {
    visible(nv) {
      if (nv === false) {
        this.onClose();
      }
    }
  },
  mounted() {
    opt.listenChange && this.listenChanged(this);
  },
  computed: {
    stateName() {
      return FORM_STATUS.FORM_STATUS_NAME[this.state];
    }
  },
  methods: {
    /**
     * @param {string} type actionName
     * @param {any} payload 数据
     * @param {boolean} loading 是否loading
     */
    '$dispatch'(type, payload, loading = true) {
      loading && (this.loading = true);
      const prom = this.$store.dispatch(type, payload);
      prom.then(res => {
        this.loading = false;
        return res;
      }).catch(err => {
        this.loading = false;
        return err;
      });
      return prom;
    },
    onClose() {
      this.loading = false;
      this.isChanged = false;
      this.state = FORM_STATUS.add;
    },
    /**
     * 关闭处理
     */
    close() {
      if (this.isChanged) {
        this.$Modal.confirm({
          title: '消息',
          content: '你已做过更改,是否继续关闭？',
          onOk: () => {
            this.visible = false;
          }
        });
        return false;
      }
      this.visible = false;
    },
    forceClose() {
      this.visible = false;
    },
    show() {
      this.visible = true;
      this.isChanged = false;
      this.state = FORM_STATUS.add;
    },
    listenChanged(parent) {
      this.$el.addEventListener('input', (e) => {
        this.isChanged = true;
      });
    }
  }
});
